#encoding:utf-8
from flask import g, redirect, render_template, request, current_app, jsonify
from Info import db, constants
from Info.lib.qiuniu_image_storage import storage
from Info.models import Category, News
from Info.module.profile import profile_blu
from Info.utils.common import user_longin_data
from Info.utils.response_code import RET

@profile_blu.route('/news_list')
@user_longin_data
def news_list():
    user = g.user
    # 获取参数
    page = request.args.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1


    news_obj_list = []
    current_page = 1
    total_page = 1
    try:
        paginate=user.news_list.order_by(News.create_time.desc()).paginate(page, constants.HOME_PAGE_MAX_NEWS, False)
        news_obj_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = [news.to_review_dict() for news in news_obj_list ]
    data = {
        "news_dict_li": news_dict_li,
        "total_page": total_page,
        "current_page": current_page,
    }
    # print(news_dict_li)
    return render_template('news/user_news_list.html',data=data)


@profile_blu.route('/news_release',methods = ['GET','POST'])
@user_longin_data
def news_release():
    '''
    新闻发布
    :return:
    '''
    if request.method =='GET':
        categorys = []
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = [category.to_dict() for category in categorys]
        category_dict_li.pop(0)
        data = {
            'category_dict_li':category_dict_li
        }
        return render_template('news/user_news_release.html',data=data)
    title = request.form.get('title')
    source = '个人发布'
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方储存失败")
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="OK")

@profile_blu.route("/info")
@user_longin_data
def user_info():
    """
    返回个人中心界面
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")

    data = {
        "user_info": user.to_dict()
    }

    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info", methods=["GET", "POST"])
@user_longin_data
def user_base_info():
    """
    基本资料的渲染
    :return:
    """
    user = g.user

    if request.method == "GET":
        data = {
            "user_info": user.to_dict()
        }

        return render_template("news/user_base_info.html", data=data)

    # 以下是post请求
    params_data = request.json
    nick_name = params_data.get("nick_name")
    signature = params_data.get("signature")
    gender = params_data.get("gender")

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")
@profile_blu.route("/pic_info", methods=["GET", "POST"])
@user_longin_data
def user_pic_info():
    """
    头像显示
    :return:
    """
    user = g.user

    if request.method == "GET":
        data = {
            "user_info": user.to_dict()
        }

        return render_template("news/user_pic_info.html", data=data)

    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        # FhM348vFzqKR2Qv3Gx9SnOfC2YAL
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方上传错误")

    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存错误")

    return jsonify(errno=RET.OK, errmsg="OK", avatar_url=constants.QINIU_DOMIN_PREFIX + key)
@profile_blu.route("/pass_info", methods=["GET", "POST"])
@user_longin_data
def user_pass_info():
    """
    修改密码
    :return:
    """
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    user = g.user

    # post的逻辑
    params_data = request.json
    old_password = params_data.get("old_password")
    new_password = params_data.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user.check_password_hash(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原始密码错误")

    # 去修改用户的密码
    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="密码修改成功")
@profile_blu.route('/user_collection')
@user_longin_data
def user_collection():
    """
    显示该用户收藏的所有新闻
    :return:
    """
    user = g.user
    page = request.args.get('p',1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    news_obj_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = user.collection_news.paginate(page, constants.HOME_PAGE_MAX_NEWS, False)
        news_obj_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e :
        current_app.logger.error(e)
    news_dict_li = [news.to_dict() for news in news_obj_list]
    data = {
        'news_dict_li':news_dict_li,
        'current_page':current_page,
        'total_page':total_page
    }
    return render_template('news/user_collection.html',data=data)

